package com.bytedance.speech.speechdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

public class TyperTextView extends androidx.appcompat.widget.AppCompatTextView {

    private Paint mPaint;
    private int currentStrLength;
    private int currentStrIndex;
    /**
     * 当前文字的大小
     */
    private float mTextSize;
    private float startX = 0;
    private float startY = 0;
    /**
     * 存储分割后的文本信息
     */
    private String[] str;

    /**
     * 行距
     */
    private float rowSpacing = 60;

    public TyperTextView(Context context) {
        super(context);
    }

    public TyperTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TyperTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 初始化基本信息
     *
     */
    private void init(String text) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(this.getCurrentTextColor());
        mPaint.setStyle(Paint.Style.FILL);

        str = text.split("--");

        mTextSize = this.getTextSize();

        mPaint.setTextSize(mTextSize);

        startX = (this.getMeasuredWidth() - this.getCompoundPaddingLeft()
                - this.getPaddingLeft() - mPaint.measureText(str[0])) / 2f;
        startY = this.getBaseline();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        init(this.getText().toString());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawFrame(canvas);
    }

    //设置文本
    public void setMyText(String myText) {
        init(myText);
        this.postInvalidateDelayed(100);
    }

    protected void drawFrame(Canvas canvas) {
        for (int i = 0; i <= currentStrIndex; i++) {
            if (i < currentStrIndex) {
                canvas.drawText(str[i], 0, str[i].length(), startX, startY
                        + rowSpacing * i, mPaint);
            } else {
                canvas.drawText(str[i], 0, currentStrLength, startX, startY
                        + rowSpacing * i, mPaint);
            }
        }
        if (currentStrLength < str[currentStrIndex].length()) {
            currentStrLength++;
            this.postInvalidateDelayed(100);
        } else if (currentStrIndex < str.length - 1) {
            currentStrLength = 0;
            currentStrIndex++;
            this.postInvalidateDelayed(100);
        }

    }

}
